<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="50%"
    top="60px"
  >
    <el-form
      style="height: 500px; overflow: auto; padding-right: 20px"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '170px' : '150px'"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜品名称" prop="name">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60"><span style="color: #f56c6c; margin-right: 4px">*</span>
            菜品图<span>(支持png、jpg，建议尺寸336*252px，最多1张)</span>
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item label="" prop="coverImage">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="
                (res, file, fileList) => successHandle(res, file, fileList)
              "
              :before-upload="beforeUploadHandle"
            >
              <img
                v-if="dataForm.coverImage"
                :src="dataForm.coverImage"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="activeName == 'second'">
        <editor-vue
          :content="dataForm.feature"
          @EditorChange="getEditor"
          ref="infoIntroduceRef"
        ></editor-vue>
      </template>
      <!-- <template v-if="activeName=='third'">
            <quill-editor class="ql-container" ref="myQuillEditor" v-model="dataForm.notice" />
        </template> -->
    </el-form>

    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList2: [],
      dialogImageUrl: "",
      dialogVisible: false,
      visible: false,
      activeName: "first",
      fishOptions: [],
      dataForm: {
        id: "",
        name: "",
        coverImage: "",
        foodId: this.$store.state.user.MerchantId,
      },
    };
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        coverImage: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        notice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        fishermanId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  components: {
    editorVue,
  },
  watch: {
    activeName(newval, oldval) {
      if (newval == "second") {
        this.$nextTick(() => {
          this.$refs.infoIntroduceRef.init();
        });
      }
    },
  },
  created() {},
  methods: {
    getEditor(val) {
      this.dataForm.information = val;
    },
    //预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },
    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.successHandle(res.data);
          }
        });
      }
    },
    // 上传成功
    successHandle(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.coverImage = res.data.url;
    },
    init() {
      this.visible = true;
      this.getFishName();
      this.$nextTick(() => {
        this.fileList2 = [];
        this.activeName = "first";
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    getFishName() {
      this.$http
        .get("/scenic/fisherman/page", {
          params: {
            page: 1,
            limit: -1,
            merchantType: 10,
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.fishOptions = res.data.data.list;
          }
        });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/sys/isfoodsuggest/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        console.log("====================================");
        console.log(this.dataForm);
        console.log("====================================");
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/sys/isfoodsuggest",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style lang="scss" scoped>
h3 {
  padding: 30px 0 15px;
  width: 94%;
  margin: 0 auto 30px;
  border-bottom: 1px solid #ddd;
  color: #303133;
  font-size: 22px;
  overflow: hidden;
}

.aui-content .ql-container {
  height: auto;
}

.ql-container.ql-snow {
  height: 500px;
}

.rooms .item {
  display: inline-block;
  margin-right: 15px;
  position: relative;

  .el-icon-error {
    position: absolute;
    right: 6px;
    top: -6px;
    font-size: 20px;
    color: #dd0606;
  }
}
</style>
